#include "LoadMenu.h"
#include "StringUtilities.h"
#include "PrintUtilities.h"
#include "MenuManager.h"
#include "GameControls.h"

#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>


LoadMenu::LoadMenu(MenuManager* const i_menuManager)
	: Menu(i_menuManager)
{
}

void LoadMenu::CalculateSlots() const
{
	for(size_t i = 0; i < Consts::NUM_SAVE_SLOT; ++i)
	{
		STD::stringstream ss;
		ss << "./save/save_" << i << ".txt";

		STD::fstream f(ss.str().c_str(), STD::ios_base::in);

		m_slots[i] = f.is_open();


		if (m_slots[i])
		{
			struct _stat s;
			_stat(ss.str().c_str(), &s);
			
			char timebuf[26];
			ctime_s(timebuf, 26, &s.st_mtime);

			m_saveNames[i] = STL::string(timebuf);
		}

		f.close();
	}
}

void LoadMenu::Draw() const
{
	CalculateSlots();

	STD::cout	<< Print::Title(" LOAD MENU:") << STD::endl << STD::endl;

	STD::stringstream ss;

	for(size_t i = 0; i < Consts::NUM_SAVE_SLOT; ++i)
	{
		ss << " " << i+1 << ") " << ((m_slots[i]) ? (m_saveNames[i]) : "empty slot.\n");
	}
	ss << "\n 0) Return to previous menu.";

	STD::cout	<< Print::Options(ss.str().c_str()); 

	STD::cout	<< " Selection: ";
}

bool LoadMenu::Input(const STL::string& i_input)
{
	int res = Utilities::StringToInt(i_input);

	if(res == 0)
	{
		GetMM()->PopMenu();
		return true;
	}

	if(res < 0 || res > Consts::NUM_SAVE_SLOT)
		return false;

	--res;

	if(!m_slots[res])
		return false;

	STD::stringstream ss;
	ss << "./save/save_" << res << ".txt";

	if(!GetMM()->GetGameControls()->Load(ss.str().c_str()))
		return false;

	GetMM()->SetMenu(GetMM()->GetMainMenu());

	return true;
}